package com.innovation.ic.im.end.data.schedule;

import com.innovation.ic.im.end.base.model.erp9_sqlserver.Erp9Admins;
import com.innovation.ic.im.end.base.model.erp9_sqlserver.Erp9MapsStructure;
import com.innovation.ic.im.end.base.model.erp9_sqlserver.Erp9Structures;
import com.innovation.ic.im.end.base.model.im_erp9.Group;
import com.innovation.ic.im.end.base.model.im_erp9.RefGroupAccount;
import com.innovation.ic.im.end.base.model.im_erp9.RefGroupAccountPrivilege;
import com.innovation.ic.im.end.base.pojo.ServiceResult;
import com.innovation.ic.im.end.base.pojo.constant.Erp9StructuresStatus;
import com.innovation.ic.im.end.base.pojo.constant.TreeNodeType;
import com.innovation.ic.im.end.base.pojo.im_erp9.AccountResultByStaffIdNotNullPojo;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Configuration
@EnableScheduling
public class ImportDefaultGroupTask extends AbstractSchedule {
    private static final Logger log = LoggerFactory.getLogger(ImportDefaultGroupTask.class);

    /**
     * 首先删除本系统所有的默认群组，然后从erp9项目中导入组织机构的数据，并生成默认的群组，包括每个组的成员
     */
    @Scheduled(cron = "0 20 2 * * ?")
//    @Scheduled(fixedRate = 60000000)
//    @Scheduled(cron = "0 10 14 * * ?")
    private void importDefaultGroup() {
        try {
            InterProcessMutex lock = new InterProcessMutex(curatorFramework, zookeeperPathDataParamConfig.getImportDefaultGroup());
            if (lock.acquire(zookeeperParamConfig.getWaitingLockTime(), TimeUnit.SECONDS)) {
                log.info("定时任务开启：删除本系统所有的默认群组，然后从erp9项目中导入组织机构的数据，并生成默认的群组，包括每个组的成员");

                // 删除group表中所有数据
                groupService.truncateTable();
                log.info("默认群组删除完成");

                // 删除ref_group_account表中所有数据
                log.info("删除ref_group_account表中所有数据");
                refGroupAccountService.truncateTable();
                log.info("删除ref_group_account表中所有数据完成");

                // 删除ref_group_account_privilege表中所有数据
                log.info("删除ref_group_account_privilege表中所有数据");
                refGroupAccountPrivilegeService.truncateTable();
                log.info("删除ref_group_account_privilege表中所有数据完成");

                // 从erp9系统中查找所有部门记录
                ServiceResult<List<Erp9Structures>> erp9StructuresListServiceResult = erp9StructuresService.findByStatus(Erp9StructuresStatus.AVAILABLE);
                if (null != erp9StructuresListServiceResult
                        && null != erp9StructuresListServiceResult.getResult()
                        && erp9StructuresListServiceResult.getResult().size() != 0) {
                    List<Erp9Structures> erp9StructuresList = erp9StructuresListServiceResult.getResult();
                    for (int i = 0; i < erp9StructuresList.size(); i++) {
                        Erp9Structures erp9Structures = erp9StructuresList.get(i);
                        // 保存群组，并返回id
                        Group group = new Group();
                        group.setId(erp9Structures.getId());
                        group.setName(erp9Structures.getName());
//                group.setType(GroupType.DEFAULT);
                        ServiceResult<String> idServiceResult = groupService.saveGroupReturnId(group);
                        // 查找这个部门中的直接子节点的所有账号，并保存到ref_group_account表中
                        String erp9StructuresId = erp9Structures.getId();
                        ServiceResult<List<Erp9MapsStructure>> listServiceResult = erp9MapsStructureService.findByStructureID(erp9StructuresId);
                        if (null != listServiceResult && null != listServiceResult.getResult()
                                && listServiceResult.getResult().size() != 0) {
                            List<Erp9MapsStructure> erp9MapsStructureList = listServiceResult.getResult();
                            for (int j = 0; j < erp9MapsStructureList.size(); j++) {
                                Erp9MapsStructure erp9MapsStructure = erp9MapsStructureList.get(j);
                                ServiceResult<List<Erp9Admins>> serviceResult = erp9AdminsService.findByStaffId(erp9MapsStructure.getStaffID());
                                if (null != serviceResult && null != serviceResult.getResult()
                                        && serviceResult.getResult().size() != 0) {
                                    List<Erp9Admins> erp9AdminsList = serviceResult.getResult();
                                    for (int x = 0; x < erp9AdminsList.size(); x++) {
                                        // 保存RefGroupAccount对象
                                        Erp9Admins erp9Admins = erp9AdminsList.get(x);
                                        RefGroupAccount refGroupAccount = new RefGroupAccount();
                                        refGroupAccount.setAccountId(erp9Admins.getId());
                                        refGroupAccount.setUsername(erp9Admins.getUsername());
                                        refGroupAccount.setGroupId(idServiceResult.getResult());
                                        refGroupAccountService.saveRefGroupAccount(refGroupAccount);
                                    }
                                }
                            }
                        }
                        // 查找这个部门的所有子部门，然后保存所有子部门的所有账号
                        ServiceResult<List<Erp9Structures>> serviceResult = erp9StructuresService.findByFatherId(erp9Structures.getId(), Erp9StructuresStatus.AVAILABLE);
                        if (null != serviceResult && null != serviceResult.getResult()
                                && serviceResult.getResult().size() != 0) {
                            List<Erp9Structures> childErp9StructuresList = serviceResult.getResult();
                            for (int j = 0; j < childErp9StructuresList.size(); j++) {
                                Erp9Structures childErp9Structures = childErp9StructuresList.get(j);
                                this.recursiveImportDefaultGroup(idServiceResult.getResult(), childErp9Structures.getId());
                            }
                        }
                    }
                }

                // 查找管理员节点的所有账号
                ServiceResult<List<Erp9Admins>> erp9AdminsListServiceResult = erp9AdminsService.findByStaffIdIsNull();
                if (null != erp9AdminsListServiceResult && null != erp9AdminsListServiceResult.getResult()
                        && erp9AdminsListServiceResult.getResult().size() != 0) {
                    // 保存管理员群组
                    Group group = new Group();
                    group.setId(TreeNodeType.ADMIN_NODE_ID);
                    group.setName(TreeNodeType.ADMIN_NODE_NAME);
//            group.setType(GroupType.DEFAULT);
                    group.setMembership(erp9AdminsListServiceResult.getResult().size());
                    ServiceResult<String> idServiceResult = groupService.saveGroupReturnId(group);
                    // 保存管理员群组的所有账号
                    for (int i = 0; i < erp9AdminsListServiceResult.getResult().size(); i++) {
                        RefGroupAccount refGroupAccount = new RefGroupAccount();
                        refGroupAccount.setGroupId(idServiceResult.getResult());
                        refGroupAccount.setUsername(erp9AdminsListServiceResult.getResult().get(i).getUsername());
                        refGroupAccount.setAccountId(erp9AdminsListServiceResult.getResult().get(i).getId());
                        refGroupAccountService.saveRefGroupAccount(refGroupAccount);
                    }
                }

                // 更新group_表的membership字段
                groupService.updateMembershipSelectRefGroupAccount();

                // 查询员工ID不为空的所有数据,获取所属机构信息,将数据插入到ref_group_account_privilege表中
                getDataInsertRefGroupAccountPrivilege();

                log.info("定时任务结束：importDefaultGroup方法执行完成");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询员工ID不为空的所有数据,获取所属机构信息,将数据插入到ref_group_account_privilege表中
     */
    private void getDataInsertRefGroupAccountPrivilege() {
        // 查询员工ID不为空的所有数据
        log.info("-----查询员工ID不为空的所有数据开始-----");
        ServiceResult<List<AccountResultByStaffIdNotNullPojo>> listServiceResult = erp9AdminsService.getAccountByStaffIdIsNotNull();
        List<AccountResultByStaffIdNotNullPojo> result = listServiceResult.getResult();
        if (result != null && result.size() > 0) {
            log.info("-----查询员工ID不为空的所有数据结束,查询到员工结果数据条数:[{}]-----", result.size());
            List<RefGroupAccountPrivilege> list = new ArrayList<RefGroupAccountPrivilege>();
            for (AccountResultByStaffIdNotNullPojo accountResultByStaffIdNotNullPojo : result) {
                // 添加当前部门下的账号对默认群组的权限信息
                RefGroupAccountPrivilege refGroupAccountPrivilege = new RefGroupAccountPrivilege();
                BeanUtils.copyProperties(accountResultByStaffIdNotNullPojo, refGroupAccountPrivilege);
                list.add(refGroupAccountPrivilege);

                // 查询当前部门下属部门数据
                ServiceResult<List<Erp9Structures>> serviceResult = erp9StructuresService.findByFatherId(accountResultByStaffIdNotNullPojo.getGroupId(), Erp9StructuresStatus.AVAILABLE);
                log.info("查询当前部门下属部门数据,当前部门groupId:[{}]", accountResultByStaffIdNotNullPojo.getGroupId());
                if(serviceResult.getResult() != null && serviceResult.getResult().size() > 0){
                    log.info("部门groupId:[{}],子部门数量:[{}]", accountResultByStaffIdNotNullPojo.getGroupId(), serviceResult.getResult().size());
                    // 添加下属部门下的账号对默认群组的权限信息
                    List<Erp9Structures> listErp9Structures = serviceResult.getResult();
                    for(Erp9Structures erp9Structures: listErp9Structures){
                        RefGroupAccountPrivilege groupAccountPrivilege = new RefGroupAccountPrivilege();
                        groupAccountPrivilege.setAccountId(accountResultByStaffIdNotNullPojo.getAccountId());
                        groupAccountPrivilege.setUsername(accountResultByStaffIdNotNullPojo.getUsername());
                        groupAccountPrivilege.setGroupId(erp9Structures.getId());
                        list.add(groupAccountPrivilege);
                    }
                }else{
                    log.info("部门groupId:[{}]的子部门数量为0", accountResultByStaffIdNotNullPojo.getGroupId());
                }
            }
            // 插入账号对默认群组的权限表数据
            if(list.size() > 0){
                log.info("-----插入账号对默认群组的权限表数据开始-----");
                ServiceResult<Integer> integerServiceResult = refGroupAccountPrivilegeService.insertRefGroupAccountPrivilegeList(list);
                log.info("-----插入账号对默认群组的权限表数据开始结束,数据入库条数:[{}]-----", integerServiceResult.getResult());
            }
        } else {
            log.info("查询员工ID不为空的所有数据完成,查询到的数据结果条数为0");
        }
    }

    /**
     * 递归调用
     *
     * @param groupId
     * @param erp9StructuresId
     */
    private void recursiveImportDefaultGroup(String groupId, String erp9StructuresId) {
        // 查找这个部门中的直接子节点的所有账号，并保存到ref_group_account表中
        ServiceResult<List<Erp9MapsStructure>> listServiceResult = erp9MapsStructureService.findByStructureID(erp9StructuresId);
        if (null != listServiceResult && null != listServiceResult.getResult()
                && listServiceResult.getResult().size() != 0) {
            List<Erp9MapsStructure> erp9MapsStructureList = listServiceResult.getResult();
            for (int j = 0; j < erp9MapsStructureList.size(); j++) {
                Erp9MapsStructure erp9MapsStructure = erp9MapsStructureList.get(j);
                ServiceResult<List<Erp9Admins>> serviceResult = erp9AdminsService.findByStaffId(erp9MapsStructure.getStaffID());
                if (null != serviceResult && null != serviceResult.getResult()
                        && serviceResult.getResult().size() != 0) {
                    List<Erp9Admins> erp9AdminsList = serviceResult.getResult();
                    for (int x = 0; x < erp9AdminsList.size(); x++) {
                        // 保存RefGroupAccount对象
                        Erp9Admins erp9Admins = erp9AdminsList.get(x);
                        RefGroupAccount refGroupAccount = new RefGroupAccount();
                        refGroupAccount.setAccountId(erp9Admins.getId());
                        refGroupAccount.setUsername(erp9Admins.getUsername());
                        refGroupAccount.setGroupId(groupId);
                        refGroupAccountService.saveRefGroupAccount(refGroupAccount);
                    }
                }
            }
        }
        // 查找这个部门的所有子部门，然后保存所有子部门的所有账号
        ServiceResult<List<Erp9Structures>> serviceResult = erp9StructuresService.findByFatherId(erp9StructuresId, Erp9StructuresStatus.AVAILABLE);
        if (null != serviceResult && null != serviceResult.getResult()
                && serviceResult.getResult().size() != 0) {
            List<Erp9Structures> childErp9StructuresList = serviceResult.getResult();
            for (int j = 0; j < childErp9StructuresList.size(); j++) {
                Erp9Structures childErp9Structures = childErp9StructuresList.get(j);
                this.recursiveImportDefaultGroup(groupId, childErp9Structures.getId());
            }
        }
    }
}